package com.diko.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diko.commonUtils.JwtUtils;
import com.diko.commonUtils.MD5;
import com.diko.config.exceptionhandler.myException;
import com.diko.ucenter.entity.Member;
import com.diko.ucenter.entity.Member2;
import com.diko.ucenter.entity.vo.LoginVo;
import com.diko.ucenter.entity.vo.RegisterVo;
import com.diko.ucenter.entity.vo.SocialUserVo;
import com.diko.ucenter.mapper.Member2Mapper;
import com.diko.ucenter.service.Member2Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diko.ucenter.utils.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Emma-Li
 * @since 2021-03-28
 */
@Service
public class Member2ServiceImpl extends ServiceImpl<Member2Mapper, Member2> implements Member2Service {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Member2 getByOpenid(String openid) {
        QueryWrapper<Member2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        Member2 member2 = baseMapper.selectOne(queryWrapper);
        return member2;
    }
    /*
     * 会员登录
     * */
    @Override
    public String login(LoginVo loginVo) {
        String mobile=loginVo.getMobile();
        String password=loginVo.getPassword();

        //校验参数
        if(StringUtils.isEmpty(mobile)||
                StringUtils.isEmpty(password)
        ){
            throw new myException(20001,"参数错误");

        }

        //获取会员
        Member2 member2=baseMapper.selectOne(new QueryWrapper<Member2>().eq("mobile",mobile));
        if(null==member2){
            throw new myException(20001,"会员不存在");
        }

        //校验密码
        if(!MD5.encrypt(password).equals(member2.getPassword())) {
            throw new myException(20001,"密码错误");
        }

        //校验是否被禁用
        if(member2.getIsDisabled()) {
            throw new myException(20001,"校验被禁用");
        }

        //使用JWT生成token字符串
        String token = JwtUtils.getJwtToken(member2.getId(), member2.getNickname());
        return token;
    }

    /*
     * 会员注册
     * */
    @Override
    public void register(RegisterVo registerVo) {
        //获取注册信息，进行校验
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();
//        String check;
//        if(registerVo.getCheck().equals("老师")){
//            check="老师";
//        }else{
//            check="学生";
//        }

        //校验参数
        if(StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(code)) {
            throw new myException(20001,"参数错误");
        }

        //校验校验验证码
        //从redis获取发送的验证码
        String mobileCode = redisTemplate.opsForValue().get(mobile);
        if(!code.equals(mobileCode)) {
            throw new myException(20001,"校验码已销毁");
        }

        //查询数据库中是否存在相同的手机号码
        Integer count = baseMapper.selectCount(new QueryWrapper<Member2>().eq("mobile", mobile));
        if(count.intValue() > 0) {
            throw new myException(20001,"已存在相同手机号");
        }

        //添加注册信息到数据库
        Member2 member2 = new Member2();
        member2.setNickname(nickname);
        member2.setMobile(registerVo.getMobile());
        member2.setPassword(MD5.encrypt(password));
        member2.setIsDisabled(false);
        member2.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        member2.setSignification(2);
        this.save(member2);
    }

    @Override
    public Member2 login(SocialUserVo socialUserVo) {
        String uid = socialUserVo.getUid();
        // 1、判断当前社交用户是否在本系统已经注册过
        Member2 member2 = this.baseMapper.selectOne(new QueryWrapper<Member2>().eq("social_uid", uid));
        if (member2 != null) { // 直接登录
            Member2 memberEntity_update = new Member2();
            memberEntity_update.setId(member2.getId());
            memberEntity_update.setAccessToken(socialUserVo.getAccess_token());
            memberEntity_update.setExpiresIn(socialUserVo.getExpires_in());
            this.baseMapper.updateById(memberEntity_update);

            member2.setAccessToken(socialUserVo.getAccess_token());
            member2.setExpiresIn(socialUserVo.getExpires_in());
            return member2;
        } else { // 注册
            Member2 regist = new Member2();

            try {
                // 查询当前社交用户的信息（昵称、性别等）
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token", socialUserVo.getAccess_token());
                map.put("uid", socialUserVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 获取用户信息成功 构建系统会员信息
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String nickname = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String avatar=jsonObject.getString("profile_image_url");
                    String city=jsonObject.getString("location");

                    regist.setNickname(nickname);
                    regist.setGender("m".equalsIgnoreCase(gender)? "男" : "女");
                    regist.setAvatar(avatar);
                    regist.setCity(city);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 上面的try是为了防止远程查询用户信息失败时，也不影响本次注册！！！
            regist.setSocialUid(socialUserVo.getUid());
            regist.setAccessToken(socialUserVo.getAccess_token());
            regist.setExpiresIn(socialUserVo.getExpires_in());
            this.baseMapper.insert(regist); // 将构建的数据写入数据库
            return regist;
        }
    }

    @Override
    public Member2 getLoginInfo(String memberId) {
        Member2 member2 = baseMapper.selectById(memberId);
        //TODO 已更改
//        LoginVo loginVo = new LoginVo();
//        BeanUtils.copyProperties(member2,loginVo);
        return member2;
    }
}
